package com.ruoyi.framework.aop;

import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.project.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 挺好的 2023年06月28日 下午 16:26
 */
@Aspect
@Component
@Slf4j
public class RateLimiterAspect {


    @Autowired
    private RedisUtils redisUtils;

    @Before ("@annotation(rateLimiter)")
    public void doBefore (JoinPoint point, RateLimiter rateLimiter) throws Throwable {
        int time = rateLimiter.time();
        int count = rateLimiter.count();
        long total = 1L;

        String combineKey = this.getCombineKey(rateLimiter, point);
        try {
            if (this.redisUtils.hasKey(combineKey)) {
                total = this.redisUtils.incr(combineKey, 1);  //请求进来，对应的key加1
                if (total > count) {
                    throw new RuntimeException(rateLimiter.limitMsg());
                }
            } else {
                this.redisUtils.set(combineKey, 1, time);  //初始化key
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("网络繁忙，请稍候再试");
        }
    }

    /**
     * 获取限流key
     *
     * @param rateLimiter
     * @param point
     *
     * @return
     */
    public String getCombineKey (RateLimiter rateLimiter, JoinPoint point) {
        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP) {
            stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class <?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }
}

